<template>
  <el-dialog :title="form.id ? '批量排班' : '批量排班'" v-model="visible" :close-on-click-modal="false" draggable>
    <el-form ref="dataFormRef" :model="form" :rules="dataRules" formDialogRef label-width="90px" v-loading="loading">
      <el-row :gutter="24">
        <el-col :span="24" class="mb20">
          <el-form-item label="请选择/请输入" label-width="100px" prop="username">
            <el-select v-model="usernameOrName" placeholder="请选择/请输入工号或姓名" clearable multiple
              @change="productSelect(usernameOrName)" @clear="clearInput">
              <el-option v-for="item in usernameOrNames" :key="item.username" :label="item.username + '-' + item.name"
                :value="item.username">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8" class="mb20">
          <el-form-item label="所属班次" label-width="100px" prop="classesId">
            <el-select class="w100" clearable placeholder="请选择所属班组" v-model="form.classesId"
              @change="banCiSelect(form.classesId)">
              <el-option :key="item.id" :label="item.classesName" :value="item.id" v-for="item in banCiLists">
                {{ item.classesName }}
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="8" class="mb20">
          <el-form-item label="所属班组" label-width="100px" prop="groupId">
            <el-select class="w100" clearable placeholder="请选择所属班组" v-model="form.groupId">
              <el-option :key="item.id" :label="item.groupName" :value="item.id" v-for="item in banZuLists">
                {{ item.groupName }}
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8" class="mb20">
          <el-form-item label="当天规则" label-width="100px" prop="ruleId">
            <el-select class="w100" clearable placeholder="请选择当天规则" v-model="form.ruleId">
              <el-option :key="item.id" :label="item.ruleName" :value="item.id" v-for="item in ruleLists">
                {{ item.ruleName }}
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8" class="mb20">
          <el-form-item label="生效时间" label-width="100px" prop="effectTime">
            <el-date-picker type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD" v-model="form.effectTime"
              placeholder="请选择生效时间">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="24" class="mb20">
          <el-form-item label="排班核对" label-width="100px" prop="effectTime">
            <div v-for="(item, index) in workTipsList" :key="index"
              style="display: flex;align-items:center ;width: 100%;">
              <div>{{ item.workStartTime }}</div>
              <div style="margin-left: 10px;margin-right: 10px;">至</div>
              <div>{{ item.workEndTime }}</div>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="onSubmit" :disabled="loading">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="UserClassesDialog">
import { useDict } from '/@/hooks/dict';
import { useMessage } from "/@/hooks/message";
import { formatDate } from '/@/utils/formatTime';
import { getObj, putObj, banCiList, banZuList, workTips, rulesList } from '/@/api/personnel/userClasses'
import { rule } from '/@/utils/validate';
const emit = defineEmits(['refresh']);

// 定义变量内容
const dataFormRef = ref();
const usernameOrNames = ref([]);
const selectOrNames = ref([] as any[]);
const banCiLists = ref([]);
const banZuLists = ref([]);
const ruleLists = ref([]);
const visible = ref(false)
const loading = ref(false)
const usernameOrName = ref([])
const workTipsList = ref([])
// 定义字典

// 提交表单数据
const form = reactive({
  id: '',
  username: '',
  name: '',
  classesId: '',
  groupId: '',
  ruleId: '',
  effectTime: '',
  pkDept: '',
});

// 定义校验规则
const dataRules = ref({
})

const filterName = (data: string) => {
  // getUsernameOrNames(placeId.value)

}
// 清空选择框
const clearInput = () => {
  form.username = ''
  form.name = ''
  form.pkDept = ''
  // getUsernameOrNames(placeId.value)
}

const banCiSelect = (e) => {
  form.groupId = ''
  form.ruleId = ''
  workTipsList.value = []
  getBanZuList(e)
  getRuleList(e)
}

const productSelect = (e) => {

  console.log('e===', e);
  selectOrNames.value = []
  for (const items in e) {
    console.log('items', e[items]);

    var index = usernameOrNames.value.findIndex(item => item.username === e[items])
    if (index != -1) {
      let aaa = {
        id: e[items],
        username: usernameOrNames.value[index].username,
        name: usernameOrNames.value[index].name,
        pkDept: usernameOrNames.value[index].pkDept
      }
      selectOrNames.value.push(aaa)
    }
  }

}
// 打开弹窗
const openDialog = (users: []) => {
  console.log('users', users);
  usernameOrName.value = []
  usernameOrNames.value = []
  selectOrNames.value = []
  usernameOrNames.value = users
  // placeId.value = users == null ? '' : users
  visible.value = true
  for (const key in users) {
    usernameOrName.value.push(users[key].username)
    let aaa = {
      username: users[key].username,
      name: users[key].name,
      pkDept: users[key].pkDept
    }
    selectOrNames.value.push(aaa)
  }
  form.effectTime = formatDate(new Date(), 'YYYY-mm-dd')
  // 重置表单数据
  nextTick(() => {
    dataFormRef.value?.resetFields();
  });
  getBanCiList()

};

const getBanCiList = () => {
  banCiList().then((res: any) => {
    banCiLists.value = res.data.records
  })
}

const getBanZuList = (e) => {
  banZuList({ classesId: e }).then((res: any) => {
    banZuLists.value = res.data.records
  })
}
const getRuleList = (e) => {
  rulesList({ classesId: e }).then((res: any) => {
    ruleLists.value = res.data.records
  })
}

watch(form, () => {
  console.log('form', form);

  if (form.classesId != '' && form.groupId != '' && form.ruleId != '' && form.effectTime != '') {
    workTips(form).then((res: any) => {
      workTipsList.value = res.data
    })
  }
})

// 提交
const onSubmit = async () => {
  const valid = await dataFormRef.value.validate().catch(() => { });
  if (!valid) return false;
  if (selectOrNames.value.length < 1) {
    useMessage().error('请选择人员');
    return
  }
  if (form.classesId == '') {
    useMessage().error('请选择班次');
    return
  }
  if (form.groupId == '') {
    useMessage().error('请选择班组');
    return
  }
  if (form.ruleId == '') {
    useMessage().error('请选择规则');
    return
  }
  if (form.effectTime == '') {
    useMessage().error('请选择时间');
    return
  }
  const submitList = [] as any[]
  for (let index = 0; index < selectOrNames.value.length; index++) {

    submitList.push({
      // id: selectOrNames.value[index].id,
      username: selectOrNames.value[index].username,
      name: selectOrNames.value[index].name,
      classesId: form.classesId,
      groupId: form.groupId,
      ruleId: form.ruleId,
      effectTime: form.effectTime,
      pkDept: selectOrNames.value[index].pkDept
    })
  }

  try {
    loading.value = true;
    await putObj(submitList).then((res: any) => {
      useMessage().success('排班成功');
      visible.value = false;
      emit('refresh');
    })

    // useMessage().success(form.id ? '修改成功' : '添加成功');
    // visible.value = false;
    // emit('refresh');
  } catch (err: any) {
    useMessage().error(err.msg);
  } finally {
    loading.value = false;
  }
};


// 初始化表单数据
const getuserClassesData = (id: string) => {
  // 获取数据
  loading.value = true
  getObj(id).then((res: any) => {
    Object.assign(form, res.data)
    getBanZuList(res.data.classesId)
    getRuleList(res.data.classesId)
  }).finally(() => {
    loading.value = false
  })
};

// 暴露变量
defineExpose({
  openDialog
});
</script>